package com.feichuang.chineseWoodCarving.controller;

import java.io.IOException;
import java.util.Enumeration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.better517na.commons.Response;
import com.better517na.commons.StatusCode;
import com.better517na.logcompontent.business.LogBusiness;
import com.better517na.logcompontent.factory.BLogFactory;
import com.better517na.logcompontent.model.MLogException;
import com.better517na.logcompontent.util.ExceptionLevel;
import com.better517na.logcompontent.util.TrackIdManager;
import com.feichuang.chineseWoodCarving.business.IUserBusiness;
import com.feichuang.chineseWoodCarving.model.MRegistryVo;
import com.feichuang.chineseWoodCarving.model.MUser;
import com.feichuang.chineseWoodCarving.util.StringUtil;
import com.google.gson.Gson;

@Controller
@RequestMapping(value = "/User")
public class UserController {

    /**
     * . 注入登录服务
     */
    @Resource(name = "userBusiness")
    private IUserBusiness userBusiness;

    // @RequestMapping(value = "/Login")
    // public String Login() {
    // return "Login/Login";
    // }

    /**
     * 登录方法,不带验证码登录（使用哪一个待确定）。
     * 
     * @param request
     *            request
     * @param response
     *            response
     * @param userName
     *            用户名字
     * @param passWord
     *            密码
     * @param userType
     *            用户类型，0:普通用户,企业用户
     * @return json
     */
    @RequestMapping(value = "/Login", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String Login(HttpServletRequest request, HttpServletResponse response, String userName, String passWord, String userType) {
        try {
            // 根据用户名密码查询用户，存在则将用户信息存入session并返回成功信息
            MUser userInfo = userBusiness.login(userName, passWord, Integer.valueOf(userType));
            if (userInfo != null) {
                // if (userInfo.getUserType() == 1) {
                request.getSession().setAttribute("LoginStaff", userInfo);
                // return "{\"Result\":1,\"Error\":0,\"Info\":\"登录成功\",\"RedirectUrl\":\"\"}"; //是否需要重定向待后期由超鸡冠儿决定
                return "{\"Result\":1,\"Error\":0,\"Info\":\"登录成功\"}";
                // } else {
                // return "{\"Result\":0,\"Error\":0,\"Info\":\"login_type\"}";
                // }
            }
            return "{\"Result\":0,\"Error\":0,\"Info\":\"" + "用户不存在" + "\"}";
        } catch (Exception ex) {
            // BAE好像有日志监控，这儿就暂时不记
            // TrackIdManager trackIdManager = new TrackIdManager();
            // trackIdManager.createTrackId("pt");
            // // LogBusiness logBusiness = new LogBusiness();
            // LogBusiness logBusiness = BLogFactory.getLogBusinessObject();
            // MLogException app = new MLogException(ExceptionLevel.Error, "", ex);
            // logBusiness.writeExceptionLog(app);
            return "{\"Result\":0,\"Error\":1,\"Info\":\"风速过大,登录失败!\"}";
        }
    }

    /**
     * 
     * TODO 添加方法注释.
     * 
     * @param request
     * @param response
     * @param userName
     * @param passWord
     * @param userType
     * @return String json
     */
    @RequestMapping(value = "/regist", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String registry(HttpServletRequest request, HttpServletResponse response, String registryParam) {
        Response<MUser> res = new Response<MUser>();
        Gson gson = new Gson();
        try {
            registryParam = request.getParameter("registryParam");
            if (!StringUtil.strIsNullOrEmpty(registryParam)) {
                MRegistryVo registryVo = gson.fromJson(registryParam, MRegistryVo.class);
                res = (Response<MUser>) userBusiness.registry(registryVo);
            }

        } catch (Exception e) {
            // TODO: handle exception
            res.setCode(StatusCode.ERROR);
            res.setMessage("注册失败");
        }
        return gson.toJson(res);
    }

    @Test
    public void test() {
        MRegistryVo registryVo = new MRegistryVo();
        MUser userInfo = new MUser();
        userInfo.setEmail("erfer");
        userInfo.setUserNo("fdsdfd");
        userInfo.setLoginPassword("fgfrfgw");
        registryVo.setUserType(1);
        registryVo.setUserInfo(userInfo);
        Gson gson = new Gson();

        String ddd = gson.toJson(registryVo);
        System.out.println(ddd);

    }

    /**
     * 登录方法，带验证码登录（使用哪一个待确定）。
     * 
     * @param request
     *            request
     * @param response
     *            response
     * @param userName
     *            用户名字
     * @param passWord
     *            密码
     * @param validata
     *            验证码
     * @param loginNum
     *            loginNum
     * @param userType
     *            用户类型，0:普通用户,企业用户
     * @return json
     */
    @RequestMapping(value = "/loginVaildata", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String loginVaildata(HttpServletRequest request, HttpServletResponse response, String userName, String passWord, String validata, String loginNum, String userType) {
        try {
            // loginNum 暂时考虑登录方式为 第一次登录不需要使用验证码，若第一次输入用户名密码错误则要求输入验证码。在用户使用体验和安全性之间做平衡
            String tipMessage = checkData(request, response, userName, passWord, validata, loginNum);
            if (!"".equals(tipMessage)) {
                return "{\"Result\":0,\"Error\":0,\"Info\":\"" + tipMessage + "\"}";
            }
            // 根据用户名密码查询用户，存在则将用户信息存入session并返回成功信息
            MUser userInfo = userBusiness.login(userName, passWord, Integer.valueOf(userType));
            if (userInfo != null) {
                if (userInfo.getUserType() == 1) {
                    request.getSession().setAttribute("LoginStaff", userInfo);
                    // return "{\"Result\":1,\"Error\":0,\"Info\":\"登录成功\",\"RedirectUrl\":\"\"}"; //是否需要重定向待后期由超鸡冠儿决定
                    return "{\"Result\":1,\"Error\":0,\"Info\":\"登录成功\"}";
                } else {
                    return "{\"Result\":0,\"Error\":0,\"Info\":\"login_type\"}";
                }
            }
            return "{\"Result\":0,\"Error\":0,\"Info\":\"" + "用户不存在" + "\"}";
        } catch (Exception ex) {
            // BAE好像有日志监控，这儿就暂时不记
            // TrackIdManager trackIdManager = new TrackIdManager();
            // trackIdManager.createTrackId("pt");
            // // LogBusiness logBusiness = new LogBusiness();
            // LogBusiness logBusiness = BLogFactory.getLogBusinessObject();
            // MLogException app = new MLogException(ExceptionLevel.Error, "", ex);
            // logBusiness.writeExceptionLog(app);
            return "{\"Result\":0,\"Error\":1,\"Info\":\"login_error\"}";
        }
    }

    /**
     * 
     * @param request
     *            request对象
     * @param txtValidateCode
     *            前台传过来的验证码
     * @param txtUser
     *            前台传过来的用户名
     * @param txtPwd
     *            前台传过来的密码
     * @return 验证标志位
     */
    public String checkData(HttpServletRequest request, HttpServletResponse response, String userName, String passWord, String validata, String loginNum) {
        // 验证码生成不成功
        if (null == request.getSession().getAttribute("rand")) {
            return "validata_error";
        }

        String validateCode = request.getSession().getAttribute("rand").toString();
        /**
         * 1，验证码错误； 2，用户名为空； 3，密码为空；
         */
        if (Integer.parseInt(loginNum) > 1) {
            if ("".equals(validata)) {
                return "validata_noEmpty";
            }
            if (!validata.toUpperCase().equals(validateCode.toUpperCase())) {
                return "validata_false";
            }
        }

        if ("".equals(userName)) {
            return "userno_noEmpty";
        }
        if ("".equals(passWord)) {
            return "password_noEmpty";
        }

        return "";
    }

    // /**
    // * 验证码
    // *
    // * @param request
    // * request
    // * @param response
    // * response
    // * @throws IOException
    // * IOException
    // */
    // @RequestMapping("/Validate")
    // public void Validate(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // try {
    // new RandImgCreater(response, request).createRandImage();
    // } catch (Exception ex) {
    // } finally {
    // }
    // }

    /**
     * .
     * 
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @return String
     */
    @RequestMapping("/LoginOut")
    public String LoginOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Enumeration em = (Enumeration) request.getSession().getAttributeNames();
            while (em.hasMoreElements()) {
                request.getSession().removeAttribute(em.nextElement().toString());
            }
        } catch (Exception ex) {
            TrackIdManager trackIdManager = new TrackIdManager();
            MUser userInfo = (MUser) request.getSession().getAttribute("LoginStaff");
            if (null != userInfo) {
                trackIdManager.createTrackId(userInfo.getUserNo());
            } else {
                trackIdManager.createTrackId("pt");
            }
            LogBusiness logBusiness = BLogFactory.getLogBusinessObject();
            MLogException app = new MLogException(ExceptionLevel.Error, "", ex);
            logBusiness.writeExceptionLog(app);
        }
        return "Login/Login";
    }
}
